<?php
if(!defined("YUEXUAN_REAL_ROOT_PATH")){
	exit("Access Denied.");
}

/**
 * redis接口
 * @author tongjun
 *
 */
class ext_redis {
    private $_redis;
    public function __construct() {
    	// 连接redis
		$this->_redis = new Redis();
		$logger = ext_logger::getInstance();
		$jsonHandle = new ext_jsonHandle();
		if(!$this->_redis->connect(
				KVDB_HOST, 
				KVDB_PORT)){
			$logger->debug("连接redis失败");
			$jsonHandle->error('连接服务器失败!');
		}
    }
    
    /**
     * 添加一个key
     * @param string $identify
     * @param array $condition
     * @param mixd $value
     */
    public function add($key, $value, $cacheTime){
    	 $logger = ext_logger::getInstance();
    	 $value = json_encode($value);
    	 $rs = $this->_redis->setnx($key, $value);
    	 if($rs && $cacheTime>0){
    	 	$this->_redis->setTimeout($key, $cacheTime);
    	 }
    	 return $rs;
    }
    /**
     * 取得数据
     * @param string $identify
     * @param array $condition
     * @return mixed
     */
    public function get($key){
    	$logger = ext_logger::getInstance();
    	$logger->debug("get读取redis数据： ".$key);
    	$value = $this->_redis->get($key);
    	$value = json_decode($value, TRUE);
    	if($value===NULL){
    		$value = false;
    	}
    	return $value;
    }
    /**
     * 保存数据
     * @param string $identify
     * @param array $condition
     * @param mixed $value
     */
    public function set($key, $value, $cacheTime){
    	$logger = ext_logger::getInstance();
    	$logger->debug("set设置redis数据： ".$key.print_r($value,1));
    	$value = json_encode($value);
    	$rs = $this->_redis->set($key, $value);
    	 if($rs && $cacheTime>0){
    	 	$this->_redis->setTimeout($key, $cacheTime);
    	 }
    }
    /**
     * 删除数据
     * @param string $identify
     * @param array $condition
     */
    public function delete($key){
    	 $logger = ext_logger::getInstance();
    	 $logger->debug("删除redis数据： ".$key);
    	 $this->_redis->delete($key);
    }
    
    /**
     * 增加
     * @param string $identify
     * @param array $condition
     * @param int $value
     */
    public function increment($key, $value=1){
    	 $logger = ext_logger::getInstance();
    	 $logger->debug("增加redis数据： ".$key);
    	 $this->_redis->incr($key, $value);
    }
    
    /**
     * 减少
     * @param string $identify
     * @param array $condition
     * @param int $value
     */
    public function decrement($key, $value=1){
    	 $logger = ext_logger::getInstance();
    	 $logger->debug("减少redis数据： ".$key);
    	 $this->_redis->decr($key, $value);
    }
}
